// pages/index/index.js
const {
  getUserFollowedPosts, getTypePosts, getUserById, isLikePost,recommendedPost
} = require('../../apis/api')

import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchInput: "",
    noteTotalNum: 0,
    msg1: '1',
    active: 1,
    active1: 0,
    noramalData: [],
    followData: []
  },
  onChange(event) {
    if (event.detail.name === 0) {
      wx.showLoading({  // 显示加载中loading效果 
        title: "加载中",
        mask: true  //开启蒙版遮罩
      });
      getUserFollowedPosts(this.data.token, (res) => {
        if(res.data.code===200){
          // this.setData({
          //   followData: res.data.data
          // })
          var arr = res.data.data.map((item) => {
            return new Promise((resolve) => {
              getUserById(this.data.token, item.post_owner_id, (res) => {
                if (res.data.code === 200) {
                  resolve({
                    ...item,
                    tx: res.data.data.pictureUrl,
                    name: res.data.data.userName,
                  });
                } else {
                  wx.showToast({
                    title: res.data.message,
                    icon: 'none',
                  });
                  resolve(item); // Return the original item in case of error.
                }
              });
            });
          });
          Promise.all(arr).then((updatedData) => {
            this.setData({
              followData: updatedData,
            });
    
            // 在此处处理 isLikePost 请求
            const likePromises = this.data.followData.map((item) => {
              return new Promise((resolve) => {
                isLikePost(this.data.token, item.post_id, (res) => {
                  if (res.data.code === 200) {
                    resolve({
                      ...item,
                      love: res.data.data==='true'?true:false
                    });
                  } else {
                    wx.showToast({
                      title: res.data.message,
                      icon: 'none',
                    });
                    resolve(item); // Return the original item in case of error.
                  }
                });
              });
            });
    
            Promise.all(likePromises).then((updatedDataWithLikes) => {
              this.setData({
                followData: updatedDataWithLikes,
              });
              wx.hideLoading()
              console.log(this.data.followData);
            });
          });
        }
      })
    }else{

    }
  },
  goDetail(e) {
    wx.navigateTo({
      url: '/pages/detail/detail?nid=' + e.currentTarget.dataset.nid,
    })
  },
  goDetail2(e) {
    wx.navigateTo({
      url: '/pages/detail/detail?nid=' + e.currentTarget.dataset.nid,
    })
  },
  /**
   * 搜索
   * @param {*}} e 
   */
  search(e) {
    console.log(this.data.searchInput)
    wx.navigateTo({
      url: '/pages/search/search?searchInput='+this.data.searchInput,
    })
  },
  getrecommendedPost(){
    wx.showLoading({  // 显示加载中loading效果 
      title: "加载中",
      mask: true  //开启蒙版遮罩
    });
    recommendedPost(this.data.token, (res) => {
      if (res.data.code === 200) {
      
        var arr = res.data.data.map((item) => {
          return new Promise((resolve) => {
            getUserById(this.data.token, item.post_owner_id, (res) => {
              if (res.data.code === 200) {
                resolve({
                  ...item,
                  tx: res.data.data.pictureUrl,
                  name: res.data.data.userName,
                });
              } else {
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                });
                resolve(item); // Return the original item in case of error.
              }
            });
          });
        });
        Promise.all(arr).then((updatedData) => {
          this.setData({
            noramalData: updatedData,
          });
  
          // 在此处处理 isLikePost 请求
          const likePromises = this.data.noramalData.map((item) => {
            return new Promise((resolve) => {
              isLikePost(this.data.token, item.post_id, (res) => {
                if (res.data.code === 200) {
                  resolve({
                    ...item,
                    love: res.data.data==='true'?true:false
                  });
                } else {
                  wx.showToast({
                    title: res.data.message,
                    icon: 'none',
                  });
                  resolve(item); // Return the original item in case of error.
                }
              });
            });
          });
  
          Promise.all(likePromises).then((updatedDataWithLikes) => {
            this.setData({
              noramalData: updatedDataWithLikes,
            });
            wx.hideLoading()
            console.log(this.data.noramalData);
          });
        });
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        });
      }
    });
  },
  onClick(event) {
    wx.showToast({
      title: `点击标签 ${event.detail.name}`,
      icon: 'none',
    });
    if(event.detail.name===0){
      this.getrecommendedPost()
    }
    wx.showLoading({  // 显示加载中loading效果 
      title: "加载中",
      mask: true  //开启蒙版遮罩
    });
    getTypePosts(this.data.token, parseInt(event.detail.name)-1, (res) => {
      if (res.data.code === 200) {
        // this.setData({
        //   noramalData: res.data.data
        // })
        var arr = res.data.data.map((item) => {
          return new Promise((resolve) => {
            getUserById(this.data.token, item.post_owner_id, (res) => {
              if (res.data.code === 200) {
                resolve({
                  ...item,
                  tx: res.data.data.pictureUrl,
                  name: res.data.data.userName,
                });
              } else {
                wx.showToast({
                  title: res.data.message,
                  icon: 'none',
                });
                resolve(item); // Return the original item in case of error.
              }
            });
          });
        });
        Promise.all(arr).then((updatedData) => {
          this.setData({
            noramalData: updatedData,
          });
  
          // 在此处处理 isLikePost 请求
          const likePromises = this.data.noramalData.map((item) => {
            return new Promise((resolve) => {
              isLikePost(this.data.token, item.post_id, (res) => {
                if (res.data.code === 200) {
                  resolve({
                    ...item,
                    love: res.data.data==='true'?true:false
                  });
                } else {
                  wx.showToast({
                    title: res.data.message,
                    icon: 'none',
                  });
                  resolve(item); // Return the original item in case of error.
                }
              });
            });
          });
  
          Promise.all(likePromises).then((updatedDataWithLikes) => {
            this.setData({
              noramalData: updatedDataWithLikes,
            });
            wx.hideLoading()
            console.log(this.data.noramalData);
          });
        });
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        });
      }
    });
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['username', 'userAvatar', 'email', 'token'],
      actions: ['setUsername', 'setUserAvatar', 'setEmail', 'setToken'],
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getrecommendedPost()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})